package ratelimit

import (
	"basic-go/syntax/webook/internal/service/sms"
	"basic-go/syntax/webook/pkg/limiter"
	"context"
	"errors"
)

const key = "sms-limiter"

var errLimited = errors.New("触发限流")

type SmsRateLimit struct {
	sms     sms.Service
	limiter limiter.Limiter
	//rate
	key string
}

func NewSmsRateLimit(sms sms.Service, limiter limiter.Limiter) *SmsRateLimit {
	return &SmsRateLimit{
		sms:     sms,
		key:     key,
		limiter: limiter,
	}
}

func (sL *SmsRateLimit) Send(ctx context.Context, tpl string, args []string, numbers ...string) error {
	limited, err := sL.limiter.Limit(ctx, sL.key)
	if err != nil {
		return err
	}
	if limited {
		return errLimited
	}

	return sL.sms.Send(ctx, tpl, args, numbers...)
}
